﻿using System;
using System.Collections.Generic;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting.Function.List
{

    /// <summary>
    /// lst = [1,3,5,7,9,10];
    /// element = select(lst, 3);
    /// echo(element);
    /// 
    /// the expected result is 5
    /// </summary>
    public class PickNode : FuncNode
    {
        /// <summary>
        /// 
        /// </summary>
        public PickNode()
            : base()
        {
            this.Value = "pick";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Evaluate()
        {
            int length = Parameters.Count;
            if (Parameters.Count < 2)
            {
                throw new ArgumentException(
                    "Please specify a list and the index of the element to pick.");
            }

            List<Object> lst 
                = Parameters[length-1].Evaluate() as List<Object>;
            double m = Convert.ToDouble(Parameters[length-2].Evaluate());
            int nth = Convert.ToInt32(Math.Round(m));

            if (nth > lst.Count)
            {
                throw new ArgumentException("Out of range");
            }

            return lst[nth];
        }
    }
}
